package me.codegenerator2.rest;

import me.codegenerator2.service.WWWGeneratorMysqlFromExcelService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;


/**
 * @author zhongfs
 */
@RestController
@RequestMapping("/excel/data/excelToMysql")
public class ExcelToMysqlController {
    @Autowired
    private WWWGeneratorMysqlFromExcelService generatorMysqlFromExcelService;

    @ResponseBody
    @PostMapping(value = "/result", produces = "text/plain;charset=UTF-8")
    public String code(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName, HttpServletResponse response) throws Exception {
        String result = generatorMysqlFromExcelService.generatorMysqlFromExcel(file, tableName);
        return result;
    }

    @ResponseBody
    @GetMapping("/aa")
    public String aa() throws Exception {
        String result = "aaaaaa!";
        return result;
    }

    @ResponseBody
    @GetMapping("/kk")
    public String cc() throws Exception {
        String result = "我们是工参zhuyu!";
        return result;
    }

    @ResponseBody
    @PostMapping("/zip")
    public String codewithzip(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName, HttpServletResponse response) throws Exception {
        String result = generatorMysqlFromExcelService.generatorMysqlFromExcel(file, tableName);
        String fileName = "由" + file.getName() + "生成的" + tableName + ".sql";
        byte[] data = generatorMysqlFromExcelService.generatorMysqlFromExcelZip(result, fileName);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
        return result;
    }

}
